<?php

class Session extends CI_Controller {

    var $menu;

    function __construct() {
        parent::__construct();
        //cargamos el odelo para que todas las funciones las usen si es necesario
        $this->load->model('user');
        $this->menu = $this->load->view('common/menu', array(), TRUE);
    }

    public function index() {
        $template_data['title'] = 'Bienvenido a la pagina del equipo tbw-apk.';
        $template_data['menu'] = $this->cargar_menu();
        $template_data['content'] = $this->load->view('index/index', array(), True);
        $this->load->view('templates/template', $template_data);
    }

    public function login() {

        //comprobamos que no haya una sessoin definida

        if (!isset($this->session->userdata["logged_in"])) {

            if (!$this->input->post()) {
                $this->load->helper(array('form'));
                $template_data['title'] = 'Iniciar sesión';
                $template_data['menu'] = $this->cargar_menu();
                $template_data['content'] = $this->load->view('session/login', array(), True);
                $this->load->view('templates/template', $template_data);
                return;
            }

//
// Post data received
//
            // Credentials validation
            $this->load->library('form_validation');
            $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_authenticate');

            if ($this->form_validation->run() == FALSE) {
// Authentication failed!
                $template_data['title'] = 'Inicio de sesión fallido';
                $template_data['menu'] = $this->menu;
                $template_data['content'] = $this->load->view('session/login', array(), True);
                $this->load->view('templates/template', $template_data);
            } else {
// Authentication succeed!




                redirect('/session/index', 'refresh');
            }
        } else {
            redirect('/session/index', 'refresh');
        }
    }

    public function authenticate($password) {
//  return TRUE;
        $username = $this->input->post('username');
        $this->load->model('user');
        $user = $this->user->authenticate($username, $password);
        if ($user) {
            $this->_set_session($user);
            return TRUE;
        }
        $this->form_validation->set_message('authenticate', 'Invalid username or password');
        return FALSE;
    }

    private function _set_session($user) {
        $sess_array = array('id' => $user->id, 'username' => $user->username, 'group' => $user->group);
        $this->session->set_userdata('logged_in', $sess_array);
    }

    function add_user() {



        $datauser = array(
            'name' => $this->input->post('name'),
            'surname' => $this->input->post('surname'),
            'dni' => $this->input->post('dni'),
            'adress' => $this->input->post('adress'),
            'cp' => $this->input->post('cp'),
            'city' => $this->input->post('city'),
            'province' => $this->input->post('province'),
            'sex' => $this->input->post('sex'),
            'phone' => $this->input->post('phone'),
            'birth' => $this->input->post('birth'),
            'email' => $this->input->post('email'),
            'add_card' => $this->input->post('add_card'),
            'federal_type' => $this->input->post('federeal_type'),
            'add_card_fed' => $this->input->post('add_card_fed'),
            'username' => $this->input->post('username'),
            'password' => $this->input->post('password'),
        );






        $this->user->add_user($datauser);
    }

    function cargar_menu() {
        if (!isset($this->session->userdata["logged_in"])) {//si no esta logeado se carga el menu common/menu
            return($this->load->view('common/menu', array(), TRUE));
        }
        if ($this->session->userdata["logged_in"]["group"] == "2") {

            return $this->load->view('user/menu', array(), TRUE);
        }
        if ($this->session->userdata["logged_in"]["group"] == "1") {


            return $this->load->view('admin/menu', array(), TRUE);
        }
    }

    function register() {


        if (!isset($this->session->userdata["logged_in"])) {
            if (!$this->input->post()) {
                $this->load->helper(array('form'));

                $this->load->helper(array('form'));
                $template_data['title'] = 'Registrate';
                $template_data['menu'] = $this->cargar_menu();
                $template_data['content'] = $this->load->view('session/register', array(), True);
                $this->load->view('templates/template', $template_data);


                return;
            } else {

                $this->load->library('form_validation');

                $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');

                $this->form_validation->set_rules('surname', 'Surname', 'trim|required|xss_clean');

                $this->form_validation->set_rules('dni', 'DNI', 'trim|required|xss_clean');

                $this->form_validation->set_rules('adress', 'Adress', 'trim|required|xss_clean');

                $this->form_validation->set_rules('cp', 'Postal Code', 'trim|required|xss_clean');

                $this->form_validation->set_rules('city', 'City', 'trim|required|xss_clean');

                $this->form_validation->set_rules('province', 'Province', 'trim|required|xss_clean');

                $this->form_validation->set_rules('sex', 'Sex', 'trim|required');

                $this->form_validation->set_rules('phone', 'Phone', 'trim|required|xss_clean');

                $this->form_validation->set_rules('birth', 'Date of bith', 'trim|required|xss_clean');

                $this->form_validation->set_rules('email', 'E-mail', 'trim|required|xss_clean');

                //$this->form_validation->set_rules('add_card', 'Fichero ingreso de cuota','trim|required|xss_clean');

                $this->form_validation->set_rules('federal_type', 'Tipo federativa', 'trim|required|xss_clean');

                //	$this->form_validation->set_rules('add_card_fed', 'Fichero ingreso de la federativa','trim|required|xss_clean');

                $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');

                $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');





                if ($this->form_validation->run() == true) {


                    $this->add_user();

                    $this->form_validation->set_message('register', 'Register Succeed');
                    $sess_array = array('type' => 'good', 'text' => 'Register Succeed');
                    $this->session->set_userdata('notification', $sess_array);

                    redirect('/session/login', 'refresh');
                } else {

                    $this->form_validation->set_message('register', 'Invalid username or password.Register failed');
                    $sess_array = array('type' => 'bad', 'text' => 'Register failed');
                    $this->session->set_userdata('notification', $sess_array);
                    //redirect('/session/register', 'refresh');

                    $template_data['title'] = 'Registro fallido';
                    $template_data['menu'] = $this->cargar_menu();
                    $template_data['content'] = $this->load->view('session/register', array(), true);
                    $this->load->view('templates/template', $template_data);
                }
            }
        } else {

            //si el usuario no esta registrado, entonces se le lleva al index y se le muestra un mensaje
            $sess_array = array('type' => 'bad', 'text' => 'Ya esta registrado');
            $this->session->set_userdata('notification', $sess_array);
            redirect('/session/index', 'refresh');
        }
    }

    //funcion para probar la vista con los estilos CSS y jquery aplicados a la pagina principal
    function template() {
        $this->load->view('templates/template');
    }

    public function logout() {

        $this->session->unset_userdata('id');
        $this->session->unset_userdata('username');
        $this->session->unset_userdata('group');
        $this->session->sess_destroy();
        redirect('session/login', 'refresh');
        $this->menu = $this->load->view('common/menu', array(), TRUE);
    }

    public function profile() {

        if (isset($this->session->userdata["logged_in"])) {
            $session_data = $this->session->userdata["logged_in"];
            $username = $session_data['username'];

            $sql = "SELECT *, DATE_FORMAT(birth, '%d/%m/%Y') as fechaN FROM (`user`) WHERE `username` = '" . $username . "'";
            $query = $this->db->query($sql);

            //$query = $this->db->get();

            if ($query->num_rows() == 1) {
                $rows = $query->result_array()[0];

                $template_data['menu'] = $this->cargar_menu();

                $template_data['title'] = "Profile";
                $template_data['content'] = $this->load->view('session/profile', $rows, true);
                $this->load->view('templates/template', $template_data);
                return $this;
            }
            return FALSE;
        }
    }
	
	public function delete_user(){
	
		
			$this->user->delete_user($this->input->post()['id_user']);
			redirect('/admin/list_users', 'refresh');
			
	}

	public function validate_user(){
	
		$this->user->validate_user($this->input->post()['id_user']);
		redirect('/admin/list_users', 'refresh');
	
	}
}
?>
	
